
/**
 * copyright(c) 2013 www.jiongshibaoliao.com, All Rights Reserved.
 * project: jiongshibaoliao 
 * author: 曾帅
 * date: 2014-1-5 下午06:12:21
 * version: v1.0
 */

package com.jiongshibaoliao.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiongshibaoliao.common.constants.ErrorCode;
import com.jiongshibaoliao.exception.JiongException;
import com.jiongshibaoliao.model.User;
import com.jiongshibaoliao.model.bean.UserBean;
import com.jiongshibaoliao.model.enums.ActiveStatus;
import com.jiongshibaoliao.service.UserService;
import com.jiongshibaoliao.util.JiongMD5;
import com.jiongshibaoliao.util.VerifyCode;

/**
 * @project jiongshibaoliao
 * @author 曾帅 
 * @version 1.0
 * @date 2014-1-5 下午06:12:21   
 */

@Controller
public class LoginController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(LoginController.class);
	
	@Autowired
	private UserService userService;
	
	private final static String LOGIN_FAILURES = "loginFailures";

	@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody JSONObject login(@RequestBody String jsonStr, HttpServletRequest request, ModelMap model) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		JSONObject returnJson = new JSONObject();
		int failures = request.getSession().getAttribute(LOGIN_FAILURES) == null ? 0 : Integer.parseInt(String.valueOf(request.getSession().getAttribute(LOGIN_FAILURES)));
		failures ++;
		returnJson.put(LOGIN_FAILURES, failures);
		request.getSession().setAttribute(LOGIN_FAILURES, failures);
		
		if(json == null || json.isEmpty()) {
			returnJson.put("code", ErrorCode.CODE_10001);
			return returnJson;
		}
		
		String loginName = String.valueOf(json.get("loginName"));
		String passWord = String.valueOf(json.get("passWord"));
		if(StringUtils.isBlank(loginName) || StringUtils.isBlank(passWord)) {
			returnJson.put("code", ErrorCode.CODE_10001);
			return returnJson;
		}
		
		String vcode = String.valueOf(json.get("vcode"));
		if(failures > 3 && StringUtils.isBlank(vcode)) {
			returnJson.put("code", ErrorCode.CODE_10002);
			return returnJson;
		}
		
		if(failures > 3 && (vcode.toLowerCase()).equals(String.valueOf(request.getSession().getAttribute(VerifyCode.VERIFY_CODE_KEY)).toLowerCase()) == false) {
			returnJson.put("code", ErrorCode.CODE_10003);
			return returnJson;
		}
		
		User user = null;
		try {
			user = userService.findUserByLoginNameAndPwd(loginName, JiongMD5.toMD5(passWord));
		} catch (JiongException e) {
			logger.error("login failure：", e);
			returnJson.put("code", ErrorCode.CODE_30000);
			return returnJson;
		}
		if(user == null) {
			returnJson.put("code", ErrorCode.CODE_20000);
			return returnJson;
		}
		
		if(ActiveStatus.UNACTIVE == user.getActiveStatus()) {
			returnJson.put("code", ErrorCode.CODE_10004);
			return returnJson;
		}
		
		if(ActiveStatus.FREEZE == user.getActiveStatus()) {
			returnJson.put("code", ErrorCode.CODE_10005);
			return returnJson;
		}
		
		user.setLastLoginDate(new Date());
		user.setLoginTimes(user.getLoginTimes() + 1);
		try {
			userService.modify(user);
		} catch (JiongException e) {
			logger.error("login failure：", e);
			returnJson.put("code", ErrorCode.CODE_30000);
			return returnJson;
		}
		UserBean userBean = new UserBean(user.getLoginName(), user.getNickName(), user.getEmail(), user.getMobile(), user.getBirthday(), user.getSex(), user.getHeadImgPath(), user.getUserType(), user.getActiveStatus(), user.getSingupSource(), user.getLastLoginDate(), user.getLoginTimes());
		request.getSession().setAttribute(UserBean.USER_SESSION_KEY, userBean);
		
		request.getSession().setAttribute(LOGIN_FAILURES, 0);
		returnJson.put("code", ErrorCode.CODE_10000);
		logger.info("user login, loginName=" + loginName + ", loginTime" + user.getLastLoginDate());
		
		return returnJson;
	}
	
	@RequestMapping(value = "/LogOut", method = {RequestMethod.GET, RequestMethod.POST})
	public void LogOut(HttpServletRequest request, ModelMap model) {
		UserBean userBean = (UserBean) request.getSession().getAttribute(UserBean.USER_SESSION_KEY);
		if(null != userBean) {
			request.getSession().removeAttribute(UserBean.USER_SESSION_KEY);
		}
		
		logger.info("user logout, userName=" + userBean.getLoginName());
	}
	
}
